package org.ws.task.listener.item.support;

import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.ws.task.item.ExecuteContext;
import org.ws.task.listener.item.ItemCommitListener;
import org.ws.task.model.TaskItem;
import org.ws.task.model.TaskProcessStatus;
import org.ws.task.model.protocol.CommitRequest;
import org.ws.task.model.protocol.CommitResponse;
import org.ws.task.model.protocol.CommitResult;
import org.ws.task.repository.WorkerContextRepository;

import java.util.List;

public class DefaultItemCommitListener implements ItemCommitListener {

    private static Logger log = LoggerFactory.getLogger(DefaultItemCommitListener.class.getName());

    @Override
    public void beforeCommit(CommitRequest request) {
        // nothing
    }

    /**
     * 完成提交后执行本地状态提交
     * @param request
     * @param response
     */
    @Override
    public void afterCommit(CommitRequest request, CommitResponse response) {
        String taskName = request.getTaskName();
        ExecuteContext context = WorkerContextRepository.getInstance().getContext(taskName);
        List<CommitResult> results = response.getResults();
        if(CollectionUtils.isNotEmpty(results)){
            for (CommitResult commitResult : results) {
                Long itemId = commitResult.getItemId();
                if (commitResult.getSuccess()) {
                    context.commitStatus(itemId, TaskProcessStatus.SUCCESS);
                } else {
                    context.commitStatus(itemId, TaskProcessStatus.COMMIT_FAILED);
                }
            }
        }
        else {
            List<TaskItem> items = request.getItems();
            if(CollectionUtils.isNotEmpty(items)){
                for (TaskItem item : items) {
                    context.commitStatus(item.getId(), TaskProcessStatus.COMMIT_FAILED);
                }
            }
        }
    }

    @Override
    public void onCommonError(CommitRequest request, Throwable e) {
        log.error(e.getMessage(),e);
    }
}
